package com.bdqn.easybuy1.service.user;

import com.bdqn.easybuy1.dao.UserAddressDao;
import com.bdqn.easybuy1.dao.impl.UserAddressDaoImpl;
import com.bdqn.easybuy1.entities.UserAddress;
import com.bdqn.easybuy1.param.UserAddressParam;
import com.bdqn.easybuy1.utils.JDBCUtils;
import org.apache.commons.dbutils.DbUtils;

import java.sql.Connection;
import java.sql.Date;
import java.sql.SQLException;
import java.util.List;

public class UserAddressServiceImpl implements UserAddressService {
    /**
     * 根据登录用户的id查询用户地址
     *
     * @param id
     * @return
     * @throws Exception
     */
    @Override
    public List<UserAddress> queryUserAddressList(Integer id) throws Exception {
        Connection connection = null;
        List<UserAddress> userAddressList = null;
        try {
            connection = JDBCUtils.getConnection();
            UserAddressDao userAddressDao = new UserAddressDaoImpl();
            UserAddressParam params = new UserAddressParam();
            params.setUserId(id);
            userAddressList = userAddressDao.queryUserAddressList(connection, params);
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DbUtils.closeQuietly(connection);
        }
        return userAddressList;
    }

    @Override
    public Integer addUserAddress(Integer id, String address, String remark) throws Exception {
        Connection connection = null;
        Integer userAddressId = null;
        try {
            connection = JDBCUtils.getConnection();
            UserAddressDao userAddressDao = new UserAddressDaoImpl();
            UserAddress userAddress = new UserAddress();
            userAddress.setUserId(id);
            userAddress.setAddress(address);
            userAddress.setRemark(remark);
            userAddress.setCreateTime(new Date(new java.util.Date().getTime()));

            userAddressDao.insert(connection, userAddress);
            userAddressId = userAddress.getId();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DbUtils.closeQuietly(connection);
        }
        return userAddressId;
    }

    @Override
    public UserAddress getUserAddressById(Integer id) {
        Connection connection = null;
        UserAddress userAddress = null;
        try {
            connection = JDBCUtils.getConnection();
            UserAddressDao userAddressDao = new UserAddressDaoImpl();
            userAddress = userAddressDao.getUserAddressById(connection, id);
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DbUtils.closeQuietly(connection);
            return userAddress;
        }
    }
}
